<template>
    <a-modal
        title=""
        :visible="true"
        width="40%"
        :footer="null"
        dialogClass="custom-modal"
        :maskClosable="false"
        @cancel="closeStopModal"
    >
        <a-form-model
            v-if="zzOrCp"
            :model="stopForm"
            ref="stopForm"
            :rules="stopRules"
            :colon="false"
            class="m-form-model"
            labelAlign="left"
            layout="vertical"
        >
            <a-row :gutter="10">
                <a-col :span="24" class="mb16">
                    <a-form-model-item :label="zzOrCp === 'cp' ? '撤牌原因' : '终止授牌原因'" prop="jsonRecord">
                        <a-checkbox-group v-model="stopForm.jsonRecord" :disabled="!isEdit">
                            <a-row>
                                <a-col :span="24" class="mb10" v-for="(checkItem, index) in stopCheckList" :key="index">
                                    <a-checkbox :value="checkItem.value" name="type" style="color: #243144">
                                        {{ index + 1 + '.' + checkItem.label }}
                                    </a-checkbox>
                                </a-col>
                            </a-row>
                        </a-checkbox-group>
                    </a-form-model-item>
                </a-col>
                <a-col v-if="zzOrCp === 'cp'" :span="24" class="mb16">
                    <a-form-model-item label="证明材料" prop="archive">
                        <a-upload
                            :before-upload="beforeUpload"
                            :action="uploadFileUrl"
                            name="file"
                            :multiple="false"
                            :disabled="!isEdit"
                            @change="uploadFileChange($event, 'archive')"
                            :accept="fileType"
                            :file-list="stopForm.archive"
                            :headers="{
                                token: fileToken,
                            }"
                            @preview="previewFile"
                        >
                            <a-button v-if="!stopForm.archive">
                                <a-icon type="upload" />
                                上传pdf文件
                            </a-button>
                        </a-upload>
                    </a-form-model-item>
                </a-col>
            </a-row>
        </a-form-model>
        <div class="h-end-center" v-if="isEdit">
            <a-button @click="closeStopModal" class="mr20">取消</a-button>
            <a-popconfirm title="请确认是否撤牌" ok-text="是" cancel-text="否" @confirm="chePai">
                <a-button :loading="stopModalLoading" class="mr20" type="primary">确定</a-button>
            </a-popconfirm>
        </div>
        <div class="h-end-center" v-else>
            <a-button @click="closeStopModal" class="mr20">确定</a-button>
        </div>
    </a-modal>
</template>

<script>
import { revokeList, zzspList } from '@/views/applyManage/config.js'
import { checkApi, getReason } from '@/common/api/applyManage'
import Bus from '@/common/bus.js'
import { getFileToken } from '@/common/api/common'
import url from '@/common/url-config.js'

export default {
    props: {
        record: {
            required: true,
            type: Object,
        },
        isEdit: {
            type: Boolean,
        },
        type: {},
    },
    data() {
        return {
            fileType: '.pdf',
            uploadFileUrl: url.uploadFile,
            fileToken: '',
            zzOrCp: null,

            stopModalLoading: false,
            stopCheckList: [],
            stopForm: {
                jsonRecord: [],
                archive: null,
            },
            stopRules: {
                jsonRecord: [
                    {
                        required: true,
                        message: '至少选择一条',
                    },
                ],
                archive: [
                    {
                        required: true,
                        message: '请上传证明材料',
                    },
                ],
            },
        }
    },
    mounted() {
        console.log('mounted')
        setTimeout(() => {
            this.init()
        }, 100)
    },
    methods: {
        async init() {
            if (this.isEdit) {
                this.zzOrCp = this.type
            } else {
                Bus.$emit('loadingStateChange', true)
                try {
                    let params = {
                        id: this.record.id,
                        state: this.record.cjzt,
                    }
                    let res = await getReason(params)
                    if (res.code == 200 && res.data) {
                        let obj = JSON.parse(res.data)
                        if (obj.archive) {
                            this.zzOrCp = 'cp'
                        } else {
                            this.zzOrCp = 'zz'
                        }
                        this.stopForm = obj
                    }
                } catch (e) {
                    console.log(e)
                }
                Bus.$emit('loadingStateChange', false)
            }
            if (this.zzOrCp === 'cp') {
                this.stopCheckList = revokeList
            } else {
                this.stopCheckList = zzspList
            }
        },
        previewFile(file) {
            let { uid: fileId, name: fileName } = file
            let fileType = 'pdf'
            const fileSrc = `/file/api/Preview/v1/${fileId}`
            if (fileType === 'pdf') {
                this.fileSrc = `/pdfjs-2.6.347-dist/web/viewer.html?file=${fileSrc}&saveName=${fileName}`
            } else if (fileType === 'other') {
                this.fileSrc = `https://view.officeapps.live.com/op/embed.aspx?src=https://api-file.scdem.cn/api/Preview/v1/${fileId}`
            } else {
                this.fileSrc = fileSrc
            }
            let routeUrl = this.$router.resolve({
                path: '/preview',
                query: { fileSrc: this.fileSrc },
            })
            window.open(routeUrl.href, '_blank')
        },
        uploadFileChange(info, key) {
            let fileList = [...info.fileList]
            fileList = fileList.map(file => {
                if (file.response) {
                    // Component will show file.url as link
                    file.url = file.response.url
                }
                return file
            })
            if (fileList.length > 0) {
                this.stopForm[key] = fileList
                let file = fileList[0]
                if (file.status === 'done') {
                    let fileRes = file.response.data
                    this.stopForm[key] = [
                        {
                            uid: fileRes.id,
                            url: fileRes.id,
                            name: fileRes.name,
                            status: 'done',
                        },
                    ]
                }
            } else {
                this.form[key] = null
            }
        },
        async beforeUpload(file) {
            return await getFileToken({ file })
                .then(res => {
                    this.fileToken = res?.data?.token
                    return Promise.resolve()
                })
                .catch(() => {
                    return Promise.reject()
                })
        },

        async chePai() {
            this.$refs.stopForm.validate(async valid => {
                if (valid) {
                    this.stopModalLoading = true
                    let params = {
                        jsonRecord: JSON.stringify(this.stopForm),
                        id: this.record.id,
                    }
                    if (this.zzOrCp === 'cp') {
                        let obj = {
                            archiveId: this.stopForm.archive[0].url,
                            archiveName: this.stopForm.archive[0].name,
                        }
                        params = {
                            ...params,
                            ...obj,
                        }
                    }
                    try {
                        let res = await checkApi.revoke(params)
                        if (res.code == 200) {
                            this.$message.success(res.message)
                            this.closeStopModal('reset')
                        }
                    } catch (e) {
                        console.log(e)
                    }
                    this.stopModalLoading = false
                }
            })
        },
        closeStopModal(type = null) {
            this.$emit('close', type)
        },
    },
}
</script>

<style lang="scss" scoped></style>
